/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stm32f0xx_it.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void fun_SensorInfoInit(void);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t _1mstick;
uint8_t _10mstick,_100mstick,_200mstick;
SENSORINFO_S  SensorInfo;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
  fun_SensorInfoInit();
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();
  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC_Init();
  MX_DAC1_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
	Uart_RecIT_Start();
	HAL_ADCEx_Calibration_Start(&hadc);
	ADC_Start_DMA();//触发adc dma 采集
	SetDACval(100);//DAC范围:100-4095
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  
  Usart_SendString("stm32f051 sys start \r\n");
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    if(_1mstick > 0)
    {
      _1mstick--;
      _10mstick++;
      _100mstick++;
      _200mstick++;	
	    ADC_Start_DMA();
    }
    if (_10mstick >= 10)
    {
      _10mstick = 0;
    }
     if (_100mstick >= 100)
    {
      _100mstick = 0;
    }
    if (_200mstick >= 250)
    {

      fun_LED();
      fun_DACtest();
      fun_UsartSend();
      fun_flash_test();
      _200mstick = 0;
    }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
  RCC_OscInitStruct.HSI14CalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
  RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void fun_SensorInfoInit(void)
{
  SensorInfo.Pressure.adc = 3234;
  SensorInfo.Pressure.val = 123406;
  SensorInfo.Pressure.offset = 0;
  SensorInfo.Pressure.factor = 100;
  SensorInfo.Temperature.adc = 2230;
  SensorInfo.Temperature.val = 623;
  SensorInfo.Temperature.offset = 40;
  SensorInfo.Temperature.factor = 10;
}

void fun_UsartSend(void)
{
  uint32_t Pressure = 0,Temperature = 0;
  if (UsartContinuousSendFlag == ORDER_GET_DEV_INF_hex)
  {
    Uart_Send_Pack((uint8_t *)&UartRecData,12);
  }
  if (UsartContinuousSendFlag == ORDER_GET_DEV_INF_ascii)
  {
    Usart_SendString_integer2("PreTemp",SensorInfo.Pressure.val - SensorInfo.Pressure.offset,SensorInfo.Temperature.val - SensorInfo.Temperature.offset);
  }
   if (UsartContinuousSendFlag == ORDER_GET_DEV_P_ascii)
  {
    Pressure =  SensorInfo.Pressure.val - SensorInfo.Pressure.offset * SensorInfo.Pressure.factor;
    Usart_SendString_integer("Pre",SensorInfo.Pressure.val - SensorInfo.Pressure.offset,SensorInfo.Pressure.factor);
  }
   if (UsartContinuousSendFlag == ORDER_GET_DEV_T_ascii)
  {
    Temperature =  SensorInfo.Temperature.val - SensorInfo.Temperature.offset * SensorInfo.Temperature.factor;
    Usart_SendString_integer("Temp",Temperature,SensorInfo.Temperature.factor);
  }
}

void fun_DACtest(void)
{
  static uint16_t dac_data = 100;
  if(++dac_data > 4096) dac_data = 100;
  SetDACval(dac_data);
}

void fun_LED(void)
{
  static uint8_t LEDdir = 0;
  if (LEDdir)
  {
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_8,GPIO_PIN_SET);//
    LEDdir = 0;
  }
  else
  {
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_8,GPIO_PIN_RESET);//
    LEDdir = 1;
  }
}

void fun_flash_test(void)
{
  uint8_t flashbuff[8] = {1,2,3,4,5,6,7,8};//写入数据
	uint32_t flashreadbuff[10];
  Flash_write(FLASH_USER_START_ADDR,(uint32_t *)flashbuff,8);
  flashreadbuff[0] =	Flash_Read(FLASH_USER_START_ADDR);
  //  结果 : flashreadbuff[0] = 0x4030201;
  //Usart_SendString_integer2("readflash",flashreadbuff[0],flashreadbuff[1]);
}

/**
 @brief 内部Flash页擦除
 @param pageAddress -[in] 擦除的起始地址
 @param nbPages -[in] 擦除页数
 @return 0 - 成功；-1 - 失败
*/
int Flash_ErasePage(uint32_t pageAddress, uint32_t nbPages)
{
	uint32_t pageError = 0;
	FLASH_EraseInitTypeDef eraseInit;
	eraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
	eraseInit.PageAddress = pageAddress;
	eraseInit.NbPages = 1;
	if(HAL_FLASHEx_Erase(&eraseInit, &pageError) != HAL_OK)
	{
		return -1;
	}
	return 0;
}
/**
  * @brief  写若干页
  * @param  地址
  * @param  数组
  * @param  长度,8bit
  * @retval None
  */
int Flash_write(uint32_t appxaddr,uint32_t *appbuf,uint32_t appsize)
{
	static FLASH_EraseInitTypeDef EraseInitStruct;
	uint32_t SECTORError = 0;
	uint32_t Address = 0x00;				//记录写入的地址
//	printf("\nFLASH:%d ",appbuf[0]%0x100);
//	printf("\nFLASH:%d ",appbuf[0] );
  /* 解锁 */
	HAL_FLASH_Unlock();
	
  /* 擦除 */
	EraseInitStruct.TypeErase     = FLASH_TYPEERASE_PAGES;
	EraseInitStruct.NbPages       = appsize/2048+1;
	EraseInitStruct.PageAddress   = appxaddr;
  if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK)
	{
		return -1;
	}
	
  /* 向内部FLASH写入数据 */
	Address = appxaddr;
	uint32_t i=0;
	while(Address < appxaddr + appsize)
	{
		if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address,appbuf[i]) == HAL_OK)
		{
		  Address = Address + 4;
			i+=1;
		}
		else
		{
		  /*写入出错，返回，实际应用中可加入处理 */
				return -1;
		}
	}
	
	/* 上锁 */
  HAL_FLASH_Lock();
	
	return 0;
}
uint32_t Flash_Read(uint32_t address)
{
	return *(__IO uint32_t *)address;
}


/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(char *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
